package com.monitorRoutine.monitorRoutineServer.clt;

import com.monitorRoutine.monitorRoutineServer.entity.SqlRecord;
import com.monitorRoutine.monitorRoutineServer.service.ExcelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.FileNotFoundException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/excel")
@Api(tags = "excel API")
public class ExcelController {
    @Value("${file.savePath}")
    String SAVE_PATH;
    @Autowired
    private ExcelService excelService;
    @GetMapping("/download/{fileName}")
    @ApiOperation(value = "excel-扫描")
    public boolean scanTemplate(@PathVariable String fileName) throws Exception {
         excelService.scanTemplate(fileName);
         return true;
    }

    public ResponseEntity<Resource> generateByTemplate(@PathVariable String templateFileName, @PathVariable String time) throws Exception {
//       String path= excelService.generateByTemplate(templateFileName,time);
        Path filePath = Paths.get(SAVE_PATH).resolve(templateFileName).normalize();
        Resource resource = new FileSystemResource(filePath.toFile());

        if (!resource.exists()) {
            throw new FileNotFoundException("模板不存在: " + templateFileName);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(resource.getFilename(), "UTF-8") + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .body(resource);    }

}
